﻿using System;
using System.Web.Configuration;
using System.Configuration;

namespace BBCode.Template
{
    public class Setting
    {
        /// <summary>
        /// Apps the setting.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public static T AppSetting<T>(string name)
        {
            var result = WebConfigurationManager.AppSettings[name];

            var type = typeof(T);
            switch (type.Name)
            {
                case "Int32":
                    int integerValue;
                    if (Int32.TryParse(result, out integerValue))
                        return (T)(object)integerValue;
                    return (T)(object)0;
                case "Boolean":
                    bool boolValue;
                    if (Boolean.TryParse(result, out boolValue))
                        return (T)(object)boolValue;
                    return (T)(object)false;
                default:
                    return (T)(object)result;
            }
        }

        /// <summary>
        /// Gets the section.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns></returns>
        public static ConfigurationSection GetSection(string path)
        {
            var config = WebConfigurationManager.OpenWebConfiguration("~");
            return config != null ? config.GetSection(path) : null;
        }
    }
}
